package com.sen.gulimall.member.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.sen.common.utils.PageUtils;
import com.sen.common.utils.Query;
import com.sen.gulimall.member.dao.MemberDao;
import com.sen.gulimall.member.dao.MemberLevelDao;
import com.sen.gulimall.member.entity.MemberEntity;
import com.sen.gulimall.member.entity.MemberLevelEntity;
import com.sen.gulimall.member.exception.PhoneExistException;
import com.sen.gulimall.member.exception.UsernameExistException;
import com.sen.gulimall.member.service.MemberService;
import com.sen.gulimall.member.vo.MemberLoginVo;
import com.sen.gulimall.member.vo.MemberRegistVo;
import com.sen.gulimall.member.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;


@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        long count = this.count(wrapper);
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        long count = this.count(wrapper);
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一。为了让controller能感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUsername());
        entity.setNickname(vo.getUsername());

        //密码要进行加密存储。
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他的默认信息

        //保存
        this.baseMapper.insert(entity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //去数据库查询
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginacct);
        wrapper.or();
        wrapper.eq("mobile", loginacct);
        MemberEntity entity = this.getOne(wrapper, false);

        if (entity == null) {
            //登录失败
            return null;
        }

        //1、获取到数据库的password
        String passwordDb = entity.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //2、密码匹配
        boolean matches = passwordEncoder.matches(password, passwordDb);
        if (matches) {
            return entity;
        }

        return null;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        String accessToken = socialUser.getAccess_token();
        long expiresIn = socialUser.getExpires_in();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid), false);
        if (memberEntity != null) {
            //这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(accessToken);
            update.setExpiresIn(expiresIn);
            this.updateById(update);

            memberEntity.setAccessToken(accessToken);
            memberEntity.setExpiresIn(expiresIn);
            return memberEntity;
        }

        //2、没有查到当前社交用户对应的记录，我们就需要注册一个
        MemberEntity regist = new MemberEntity();
        //3、查询当前社交用户的社交账号信息（昵称，性别等）
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("access_token", accessToken);
            paramMap.put("uid", uid);
            HttpResponse response = HttpRequest.get("https://api.weibo.com/2/users/show.json").form(paramMap).timeout(50000).execute();
            if (response.getStatus() == 200) {
                //查询成功
                String json = response.body();
                JSONObject jsonObject = JSON.parseObject(json);
                //昵称
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                //...
                regist.setNickname(name);
                regist.setGender("m".equals(gender) ? 1 : 0);
            }
        } catch (Exception e) {
            log.info("查询当前社交用户的社交账号信息，异常：{}", e);
        }

        regist.setSocialUid(socialUser.getUid());
        regist.setAccessToken(socialUser.getAccess_token());
        regist.setExpiresIn(socialUser.getExpires_in());
        this.save(regist);

        return regist;
    }

}